// FTP私有同步云盘脚本
document.addEventListener('DOMContentLoaded', function() {
    console.log("DOM已加载，初始化功能...");
    
    // 初始化下拉菜单
    initDropdowns();
    
    // 初始化闪现消息自动消失
    initFlashMessages();
    
    // 初始化表单验证
    initFormValidation();
    
    // 初始化工具提示
    initTooltips();
    
    // 添加同步目录表单的选择文件夹功能
    initFolderSelector();
});


// 下拉菜单初始化
function initDropdowns() {
    // 清除可能存在的旧事件监听器
    document.querySelectorAll('.dropdown-toggle').forEach(toggle => {
        const newToggle = toggle.cloneNode(true);
        toggle.parentNode.replaceChild(newToggle, toggle);
    });

    // 处理所有下拉菜单
    document.querySelectorAll('.dropdown-toggle').forEach(toggle => {
        toggle.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            const dropdown = this.closest('.dropdown');
            const menu = dropdown.querySelector('.dropdown-menu');

            // 先关闭所有其他下拉菜单
            document.querySelectorAll('.dropdown-menu.show').forEach(openMenu => {
                if (openMenu !== menu) {
                    openMenu.classList.remove('show');
                }
            });

            // 切换当前菜单的显示状态
            menu.classList.toggle('show');

            if (menu.classList.contains('show')) {
                // 如果菜单显示了，设置其位置
                const buttonRect = toggle.getBoundingClientRect();

                // 定位在按钮正下方
                menu.style.position = 'fixed';
                menu.style.top = `${buttonRect.bottom + window.scrollY + 5}px`;
                menu.style.left = `${buttonRect.left + window.scrollX}px`;

                // 防止超出右边界
                if (buttonRect.left + menu.offsetWidth > window.innerWidth) {
                    menu.style.left = `${window.innerWidth - menu.offsetWidth - 10}px`;
                }
            }
        });
    });
    
    // 点击页面其他区域关闭所有下拉菜单
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.dropdown')) {
            document.querySelectorAll('.dropdown-menu.show').forEach(menu => {
                menu.classList.remove('show');
            });
        }
    });
    
    // 防止点击菜单内部导致菜单关闭
    document.querySelectorAll('.dropdown-menu').forEach(menu => {
        menu.addEventListener('click', function(e) {
            if (!e.target.closest('a')) {
                e.stopPropagation();
            }
        });
    });
}

// 闪现消息自动消失
function initFlashMessages() {
    const flashMessages = document.querySelectorAll('.flash');
    
    flashMessages.forEach(message => {
        // 5秒后自动淡出
        setTimeout(() => {
            message.style.opacity = '0';
            message.style.transform = 'translateY(-10px)';
            message.style.transition = 'opacity 0.5s, transform 0.5s';
            
            // 动画结束后移除元素
            setTimeout(() => {
                message.remove();
            }, 500);
        }, 5000);
        
        // 添加关闭按钮
        const closeBtn = document.createElement('button');
        closeBtn.innerHTML = '&times;';
        closeBtn.className = 'flash-close';
        closeBtn.style.float = 'right';
        closeBtn.style.background = 'none';
        closeBtn.style.border = 'none';
        closeBtn.style.fontSize = '1.25rem';
        closeBtn.style.cursor = 'pointer';
        closeBtn.style.opacity = '0.7';
        closeBtn.style.marginLeft = '10px';
        
        closeBtn.addEventListener('click', () => {
            message.remove();
        });
        
        message.prepend(closeBtn);
    });
}

// 表单验证
function initFormValidation() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            // 检查所有必填字段
            const requiredFields = form.querySelectorAll('[required]');
            let isValid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('is-invalid');
                    
                    // 创建或更新错误信息
                    let errorMsg = field.parentNode.querySelector('.error-message');
                    if (!errorMsg) {
                        errorMsg = document.createElement('div');
                        errorMsg.className = 'error-message';
                        errorMsg.style.color = 'var(--danger-color)';
                        errorMsg.style.fontSize = '0.85rem';
                        errorMsg.style.marginTop = '0.25rem';
                        field.parentNode.appendChild(errorMsg);
                    }
                    
                    errorMsg.textContent = field.getAttribute('data-error-message') || '此字段是必填的';
                } else {
                    field.classList.remove('is-invalid');
                    const errorMsg = field.parentNode.querySelector('.error-message');
                    if (errorMsg) {
                        errorMsg.remove();
                    }
                }
            });
            
            // 如果表单无效，阻止提交
            if (!isValid) {
                e.preventDefault();
            }
        });
    });
}

// 工具提示初始化
function initTooltips() {
    console.log("初始化工具提示...");
    const tooltips = document.querySelectorAll('[data-tooltip]');
    console.log(`找到 ${tooltips.length} 个工具提示元素`);
    
    tooltips.forEach(element => {
        const tooltipText = element.getAttribute('data-tooltip');
        
        // 创建工具提示元素
        const tooltip = document.createElement('div');
        tooltip.className = 'tooltip';
        tooltip.textContent = tooltipText;
        tooltip.style.position = 'absolute';
        tooltip.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
        tooltip.style.color = 'white';
        tooltip.style.padding = '0.5rem 0.75rem';
        tooltip.style.borderRadius = '4px';
        tooltip.style.fontSize = '0.85rem';
        tooltip.style.zIndex = '1000';
        tooltip.style.opacity = '0';
        tooltip.style.visibility = 'hidden';
        tooltip.style.transition = 'opacity 0.3s, visibility 0.3s';
        tooltip.style.pointerEvents = 'none';
        
        document.body.appendChild(tooltip);
        
        // 显示工具提示
        element.addEventListener('mouseenter', () => {
            const rect = element.getBoundingClientRect();
            tooltip.style.top = `${rect.bottom + window.scrollY + 5}px`;
            tooltip.style.left = `${rect.left + window.scrollX + (rect.width / 2) - (tooltip.offsetWidth / 2)}px`;
            tooltip.style.opacity = '1';
            tooltip.style.visibility = 'visible';
        });
        
        // 隐藏工具提示
        element.addEventListener('mouseleave', () => {
            tooltip.style.opacity = '0';
            tooltip.style.visibility = 'hidden';
        });
    });
}

// 文件夹选择器
function initFolderSelector() {
    const selectFolderBtn = document.getElementById('select-folder-btn');
    const folderPathInput = document.getElementById('local_path');
    
    if (selectFolderBtn && folderPathInput) {
        selectFolderBtn.addEventListener('click', async function(e) {
            e.preventDefault();
            
            try {
                const response = await fetch('/select_folder');
                const data = await response.json();
                
                if (data.path) {
                    folderPathInput.value = data.path;
                } else if (data.error) {
                    alert('选择文件夹失败: ' + data.error);
                }
            } catch (err) {
                console.error('选择文件夹时出错:', err);
                alert('选择文件夹失败，请手动输入路径');
            }
        });
    }
}

// 确认对话框
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

// 测试FTP连接
async function testFtpConnection(formData) {
    try {
        const response = await fetch('/api/test_ftp_connection', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification(result.message, 'success');
        } else {
            showNotification(result.message, 'error');
        }
        
        return result;
    } catch (err) {
        console.error('测试FTP连接时出错:', err);
        showNotification('测试FTP连接失败: ' + err.message, 'error');
        return { success: false, message: err.message };
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = message;
    
    // 设置样式
    notification.style.position = 'fixed';
    notification.style.bottom = '20px';
    notification.style.right = '20px';
    notification.style.padding = '1rem 1.5rem';
    notification.style.borderRadius = '8px';
    notification.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    notification.style.zIndex = '9999';
    notification.style.maxWidth = '90%';
    notification.style.minWidth = '300px';
    notification.style.animation = 'slideIn 0.5s forwards';
    
    // 设置颜色
    switch (type) {
        case 'success':
            notification.style.backgroundColor = '#e8f5e9';
            notification.style.color = '#2e7d32';
            notification.style.borderLeft = '4px solid #4caf50';
            break;
        case 'error':
            notification.style.backgroundColor = '#ffebee';
            notification.style.color = '#c62828';
            notification.style.borderLeft = '4px solid #f44336';
            break;
        case 'warning':
            notification.style.backgroundColor = '#fff3e0';
            notification.style.color = '#ef6c00';
            notification.style.borderLeft = '4px solid #ff9800';
            break;
        default:
            notification.style.backgroundColor = '#e3f2fd';
            notification.style.color = '#1565c0';
            notification.style.borderLeft = '4px solid #1a73e8';
    }
    
    // 添加动画
    const style = document.createElement('style');
    style.textContent = `
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        @keyframes slideOut {
            from { transform: translateX(0); opacity: 1; }
            to { transform: translateX(100%); opacity: 0; }
        }
    `;
    document.head.appendChild(style);
    
    // 添加关闭按钮
    const closeBtn = document.createElement('button');
    closeBtn.innerHTML = '&times;';
    closeBtn.style.background = 'none';
    closeBtn.style.border = 'none';
    closeBtn.style.float = 'right';
    closeBtn.style.marginLeft = '10px';
    closeBtn.style.fontSize = '1.2rem';
    closeBtn.style.cursor = 'pointer';
    closeBtn.style.opacity = '0.7';
    closeBtn.style.transition = 'opacity 0.2s';
    
    closeBtn.addEventListener('mouseover', () => {
        closeBtn.style.opacity = '1';
    });
    
    closeBtn.addEventListener('mouseout', () => {
        closeBtn.style.opacity = '0.7';
    });
    
    closeBtn.addEventListener('click', () => {
        notification.style.animation = 'slideOut 0.5s forwards';
        setTimeout(() => {
            notification.remove();
        }, 500);
    });
    
    notification.prepend(closeBtn);
    
    // 添加到文档
    document.body.appendChild(notification);
    
    // 5秒后自动消失
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.5s forwards';
        setTimeout(() => {
            notification.remove();
        }, 500);
    }, 5000);
    
    return notification;
}